package edu.zut.main.thread;

public class DeadLock {

    public static void main(String[] args) {
        People boy = new People("boy");
        People girl = new People("girl");

        new Thread(new DeadThread(boy)).start();
        new Thread(new DeadThread(girl)).start();

    }

}

//刀 叉问题


class DeadThread implements Runnable{

    private People people;

    public DeadThread(People people) {
        this.people = people;
    }

    @Override
    public void run() {
        try {
            people.eatFood();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

//叉子
class Fork{

}

//刀子
class Knife{

}

//人
class People{

    //不管几个人，都用的是这一组刀叉
    static Fork fork = new Fork();
    static Knife knife = new Knife();

    private String name;

    public People(String name) {
        this.name = name;
    }

    //吃东西   一旦多线程中，要锁定的共享资源是多个对象时，不要嵌套锁
    public void eatFood() throws InterruptedException {
        if (name.equals("boy")){
            synchronized (knife){
                System.out.println("boy拿到了刀子");
            }
            Thread.sleep(1000);
            //boy把刀子锁起来，又想接着拿叉子
            synchronized (fork) {
                System.out.println("boy又拿到了叉子");
            }
        }

        if (name.equals("girl")){
            synchronized (fork) {
                System.out.println("girl拿到了叉子");
            }
            Thread.sleep(1000);
            synchronized (knife){
                System.out.println("girl又拿到了刀子");
            }
        }

    }

}


